package com.qf.ability.message.controller;

import com.qf.ability.message.entity.Email;
import com.qf.ability.message.entity.SkywalkingAlter;
import com.qf.ability.message.utils.SendMailUtils;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/alter")
@Slf4j
public class AlterController {

    @Value("${alter.recevers}")
    private String recevers;

    /**
     * skywalking告警
     * @return
     */
    @RequestMapping("/skywalking")
    public R skywalkingAlter(@RequestBody List<SkywalkingAlter> alters){
        log.info("[skywalking alter] - 接收到Skywalking的告警通知 - {}", alters);
        log.info("[skywalking alter] - 通知相关人员：{}", recevers);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        StringBuilder sb = new StringBuilder();
        for (SkywalkingAlter alter : alters) {
            sb.append("<hr/>")
                    .append("告警类型：").append(alter.getScope()).append("<br/>")
                    .append("告警服务：").append(alter.getName()).append("<br/>")
                    .append("告警时间：").append(simpleDateFormat.format(new Date(alter.getStartTime()))).append("<br/>")
                    .append("告警内容：").append(alter.getAlarmMessage()).append("<br/>");
        }

        Email email = new Email()
                .setSubject("服务器告警通知！")
                .setRecevers(recevers.split("\\|"))
                .setContent(sb.toString());

        //发送邮件
        SendMailUtils.sendMail(email);
        return Rs.create(Codes.SUCC);
    }
}
